package com.jingyanzi.finance.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.finance.dao.CashRefundMapper;
import com.jingyanzi.finance.dao.CashSerialMapper;
import com.jingyanzi.finance.domain.CashPayRecordDO;
import com.jingyanzi.finance.domain.CashPlaceDO;
import com.jingyanzi.finance.domain.CashRefundDO;
import com.jingyanzi.finance.entity.CashRefund;
import com.jingyanzi.finance.entity.CashRefundExample;
import com.jingyanzi.finance.entity.CashRefundExample.Criteria;
import com.jingyanzi.finance.entity.CashSerial;
import com.jingyanzi.finance.entity.CashSerialExample;
import com.jingyanzi.finance.query.CashRefundQueryDO;
import com.jingyanzi.finance.result.ResultDO;
import com.jingyanzi.finance.result.ResultSupport;
import com.jingyanzi.finance.service.IPayRecordService;
import com.jingyanzi.finance.service.IPlaceService;
import com.jingyanzi.finance.service.IRefundService;
import com.jingyanzi.finance.util.BeanUtilsExtends;
import com.jingyanzi.member.domain.CustomerDO;
import com.jingyanzi.member.domain.IntegralDO;
import com.jingyanzi.member.factory.MemberFactory;
import com.jingyanzi.member.service.ICustomerService;
import com.jingyanzi.member.service.IIntegralLogService;
import com.jingyanzi.privilege.domain.EmployeeDO;
import com.jingyanzi.privilege.factory.PrivilegeFactory;
import com.jingyanzi.privilege.service.IEmployeeService;
import com.jingyanzi.resallocation.domain.StoreDO;
import com.jingyanzi.resallocation.factory.ResFactory;
import com.jingyanzi.resallocation.service.IStoreService;
import com.jingyanzi.sys.domain.DictionariesDO;
import com.jingyanzi.sys.domain.service.ISettingService;
import com.jingyanzi.sys.factory.SysFactory;

@Service("refundService")
public class RefundServiceImpl extends BaseServiceImpl implements IRefundService {

	@Autowired
	private CashRefundMapper cashRefundMapper;
	
	@Autowired
	private CashSerialMapper cashSerialMapper;
	
	@Autowired
	private IPayRecordService payRecordService;
	
	@Autowired
	private IPlaceService placeService;
	
	private IEmployeeService getEmployeeService() {
		return PrivilegeFactory.getEmployeeService();
	}
	
	private ICustomerService getCustomerService() {
		return MemberFactory.getCustomerService();
	}
	
	private IStoreService getStoreService() {
		return ResFactory.getStoreService();
	}

	private IIntegralLogService getIntegralLogService() {
		return MemberFactory.getIntegralLogService();
	}
	
	private ISettingService getSettingService() {
		return SysFactory.getISettingService();
	}


	public ResultDO add(CashRefundDO domain) {
		
		CashRefund entity = new CashRefund();
		
		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess())
        	return result;
        
        entity.setCreatetime(Calendar.getInstance().getTime());
        entity.setModifitime(entity.getCreatetime());
        entity.setIsDelete(1);
        int r = -1;
        
      //获得会员信息
		com.jingyanzi.member
		.domain.result.ResultDO res1 = getCustomerService().get(entity.getCustomId());
		
		if(!res1.isSuccess()) {
			System.out.println("r1");
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取客户联系人失败");
			result.setSuccess(false);
			return result;
		}
		
		CustomerDO customerDO = (CustomerDO) res1.getModel(ResultDO.FIRST_MODEL_KEY);
		if(customerDO.getFirstFamilyMember() == null) {
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取客户联系人失败");
			result.setSuccess(false);
			return result;
		}
		
		entity.setCustomName(customerDO.getFirstFamilyMember().getName());
		entity.setCustomTel(customerDO.getFirstFamilyMember().getTelephone());
		
		//获取门店信息
		com.jingyanzi.resallocation.
		result.ResultDO res2 = getStoreService().get(domain.getStoreId());
		
		if(!res2.isSuccess()) {
			System.out.println("r2");
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取门店失败");
			result.setSuccess(false);
			return result;
		}
		
		StoreDO storeDO = (StoreDO) res2.getModel(ResultSupport.FIRST_MODEL_KEY);
		if(storeDO == null) {
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获取门店失败");
			result.setSuccess(false);
			return result;
		}
		
		entity.setStoreName(storeDO.getName());
		
		//获取销售员工信息
		EmployeeDO employeeDO = getEmployee(domain.getApplyId());
		
		if(employeeDO == null) {
			System.out.println("employeeDO");
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "add 获取员工信息失败");
			return result;
		}
		
		entity.setApplyName(employeeDO.getRealName());
        try {
            r = cashRefundMapper.insert(entity);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
        if (r < 1) {
        	result.setSuccess(false);
        }
 
        result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getId());
        return result;
	}

	public ResultDO modifi(CashRefundDO domain) {
		
		CashRefund entity = new CashRefund();
		
		ResultSupport result = BeanUtilsExtends.copy(domain, entity);
        if (!result.isSuccess())
        	return result;
        
        int r = -1;
        
        try {
            r = cashRefundMapper.updateByPrimaryKeySelective(entity);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
        if (r < 1) {
        	result.setSuccess(false);
        }
        
        return result;
	}

	public ResultDO remove(Integer id) {
		
		CashRefund entity = new CashRefund();
		
		ResultSupport result = new ResultSupport();
        if (!result.isSuccess())
        	return result;
        int r = -1;
        entity.setId(id);
        entity.setIsDelete(-1);
        try {
            r = cashRefundMapper.updateByPrimaryKeySelective(entity);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
        if (r < 1) {
        	result.setSuccess(false);
        }
        return result;
	}
	
	public ResultDO confirm(CashRefundDO domain) {
		
		CashRefund entity = null;

		ResultSupport result = new ResultSupport();

		//读取账单信息
		try {
			entity = cashRefundMapper.selectByPrimaryKey(domain.getId());
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "支付异常");
			return result;
		}
		System.out.println(entity);
		if (entity == null) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "支付异常");
			return result;
		}
		
		if(domain.getStatus() == 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "确认收款参数错误");
			return result;
		}
		
		CashPayRecordDO payRecordDO = new CashPayRecordDO();
		
		String tradeNO = getTradeNO(domain.getApplyId());
		
		if(tradeNO == null) {
			System.out.println("tradeNo is null");
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "获得交易流水号失败");
			return result;
		}
		
		payRecordDO.setTradeNO(tradeNO);
		String businessNO = entity.getRefundNo();
		
		payRecordDO.setBusinessNO(businessNO);
		payRecordDO.setMappingId(entity.getId());
		payRecordDO.setCashierId(entity.getApplyId());
		EmployeeDO employeeDO = getEmployee(entity.getApplyId());
		if(employeeDO == null) {
			System.out.println("employeeDO is null");
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 获取员工信息失败");
			return result;
		}
		payRecordDO.setCashierName(employeeDO.getRealName());
		payRecordDO.setCustomId(entity.getCustomId());
		payRecordDO.setCustomName(entity.getCustomName());
		payRecordDO.setCustomTel(entity.getCustomTel());
		payRecordDO.setVoucherNO(getVoucherNO());
		payRecordDO.setAmount(domain.getAmount());
		payRecordDO.setPayMethodId(domain.getPayMethodId());
		payRecordDO.setPayMethod(PAY_METHOD_NAMES.get(domain.getPayMethodId()));
		payRecordDO.setCashType(domain.getPayTypeId());
		
		payRecordDO.setRemarks(domain.getRemarks());
		//要从字典查收款类型
		//获取字典信息
		com.jingyanzi.sys.domain
		.result.ResultDO res5 = getSettingService().getDictionariesById(domain.getPayTypeId());
		if (!res5.isSuccess()) {
			System.out.println("Dictionaries is null");
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "add 获取字典信息失败");
			return result;
		}

		DictionariesDO dic = (DictionariesDO) res5.getModel(ResultSupport.FIRST_MODEL_KEY);
		
		payRecordDO.setCashTypeName(dic.getDataItem());
		
		payRecordDO.setInvoiceStatus(domain.getInvoiceStatus());
		payRecordDO.setAuthor(domain.getAuthor());
		payRecordDO.setModifi(domain.getAuthor());
		//通过收银员ID查询绑定的收银地点
		ResultDO res3 = placeService.getPlaceByEmployeeId(domain.getCashierId());
		if(!res3.isSuccess()) {
			System.out.println("Place is null");
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 获取收银地点失败");
			return result;
		}
		
		CashPlaceDO placeDO = (CashPlaceDO) res3.getModel(ResultSupport.FIRST_MODEL_KEY);
		payRecordDO.setPlaceId(placeDO.getId());
		payRecordDO.setPlaceName(placeDO.getPlaceName());
		
		ResultDO res = payRecordService.add(payRecordDO);
		
		if(!res.isSuccess()) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 添加收银记录失败");
			return result;
		}
		
		/*//生成电子票据
		if(!VoucherUtil.createRefund(domain)) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 生成票据失败");
			return result;
		}*/
		
		if(domain.getIsSms() == 1) {
			//发送短信调用短信接口
		}
		
		if(domain.getIsElectronic() == 1) {
			//调用微信接口发送电子账单
		}
		
	    //调用积分接口减去积分
		IntegralDO integralDO = new IntegralDO();
		integralDO.setMemberId(entity.getCustomId());
		integralDO.setIntegral(domain.getIntegral());
		integralDO.setOpType(2); //扣除积分
		integralDO.setOpInfo("积分抵现"); //TODO：积分扣除事由
		integralDO.setAuthor(domain.getAuthor());
		integralDO.setTradeNo(businessNO); //businessNO ? tradeNo?
		
		com.jingyanzi.member.domain.result.ResultDO res6 = getIntegralLogService().addLog(integralDO);
		
		if(!res6.isSuccess()) {
			result.setSuccess(false);
			result.setErrorCode(res6.getErrorCode());
			result.setErrorMsg(res6.getErrorMsg());
			return result;
		}
		
		int r = -1;
		
		//更新账单状态
		try {
			r = cashRefundMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "支付异常");
			return result;
		}
		
		if(r < 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "支付异常");
			return result;
		}
				
		return result;
	}

	public ResultDO get(Integer id, Integer cashierId) {
		
		CashRefund entity = new CashRefund();

		ResultSupport result = new ResultSupport();
        if (!result.isSuccess())
        	return result;
        
        try {
        	entity = cashRefundMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
        if (entity == null) {
        	result.setSuccess(false);
        }
        
        CashRefundDO cashRefundDO = getCashRefundDO(entity);
        //通过收银员ID查询绑定的收银地点
  		ResultDO res3 = placeService.getPlaceByEmployeeId(cashierId);
  		
  		if(!res3.isSuccess()) {
  			result.setSuccess(false);
  			result.setErrorCode(ResultSupport.SYSTEM_EXCEPTION_ERROR);
  			result.setErrorMsg(ResultSupport.SYSTEM_EXCEPTION_ERROR_MSG + "pay 获取收银地点失败");
  			return result;
  		}
  		
  		CashPlaceDO placeDO = (CashPlaceDO) res3.getModel(ResultSupport.FIRST_MODEL_KEY);
  		if(placeDO != null) {
  			cashRefundDO.setPlaceId(placeDO.getId());
  			cashRefundDO.setPlaceName(placeDO.getPlaceName());
  		} else {
  			cashRefundDO.setPlaceId(0);
  			cashRefundDO.setPlaceName("");
  		}
  		cashRefundDO.setCreatetime(System.currentTimeMillis() + "");
        
      
        result.setModel(ResultSupport.FIRST_MODEL_KEY, cashRefundDO);
        return result;
	}

	public ResultDO query(CashRefundQueryDO query) {
		
		ResultSupport result = new ResultSupport();

		List<CashRefund> list = null;

		CashRefundExample example = new CashRefundExample();
		
		Criteria createCriteria = example.createCriteria();
		
		createCriteria.andIsDeleteEqualTo(1);
		
		if(query.getStatus() != null) {
			if(query.getStatus() != 2) {
				createCriteria.andStatusEqualTo(query.getStatus());
			}
		}
		if(StringUtils.isNotEmpty(query.getStartTimeStamp()) &&
				StringUtils.isNotEmpty(query.getEndTimeStamp())) {
			Date startTime = new Date(Long.parseLong((query.getStartTimeStamp() + (24 * 60 * 60 * 1000))));
			Date endTime = new Date(Long.parseLong((query.getEndTimeStamp() + (24 * 60 * 60 * 1000))));
			createCriteria.andCreatetimeBetween(startTime, endTime);
		}

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = cashRefundMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}
		
		List<CashRefundDO> doList = new ArrayList<CashRefundDO>();

		try {
			list = cashRefundMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}

		doList = getCashRefundDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, doList);

		return result;
	}
	
	public CashRefundDO getCashRefundDO(CashRefund entity) {
		if (entity == null)
			return null;
		CashRefundDO dst = new CashRefundDO();
		return BeanUtilsExtends.copyProperties(dst, entity) ? dst : null;
	}
	
	public List<CashRefundDO> getCashRefundDOList(List<CashRefund> list) {
		List<CashRefundDO> result = new ArrayList<CashRefundDO>();
		if (list != null && !list.isEmpty()) {
			for (CashRefund org : list) {
				CashRefundDO org1 = getCashRefundDO(org);
				if (org1 != null) {
					org1.setCreatetime(System.currentTimeMillis() + "");
					result.add(org1);
				}
			}
		}
		return result;
	}
	
	private String getTradeNO(int emid) {
		SimpleDateFormat df = new SimpleDateFormat("YYYYMMdd");
		String dateStr = df.format(new Date());
		CashSerialExample example = new CashSerialExample();
		List<CashSerial> list = null;
		example.createCriteria().andCreatetimeEqualTo(dateStr);
		try {
			list = cashSerialMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		if(list.size() > 1) {
			return null;
		}
		
		int r = -1;
		int serialNumber = 1;
		
		if(list.size() == 0) {
			//没有流水号时创建今天的流水号
			CashSerial cashSerial = new CashSerial();
			cashSerial.setCreatetime(dateStr);
			cashSerial.setSerialNumber(serialNumber);
			try {
				r = cashSerialMapper.insertSelective(cashSerial);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		} else {
			//今天的流水号存在的时候更新
			CashSerial cashSerial = list.get(0);
			serialNumber = cashSerial.getSerialNumber() + 1;
			cashSerial.setSerialNumber(serialNumber);
			try {
				r = cashSerialMapper.updateByPrimaryKeySelective(cashSerial);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		if(r < 0) {
			return null;
		}
		
		EmployeeDO employeeDO = getEmployee(emid);
		
		if(employeeDO == null) {
			System.out.println(" Tradno employeeDO IS NULL");
			return null;
		}
		
		return dateStr + employeeDO.getWorkNo() + serialNumber;
	}
	
	public EmployeeDO getEmployee(int id) {
		//获取销售员工信息
		com.jingyanzi.privilege.
			domain.result.ResultDO res = getEmployeeService().getEmployee(id);
		
		if(!res.isSuccess()) {
			return null;
		}
		EmployeeDO employeeDO = (EmployeeDO) res.getModel(ResultSupport.FIRST_MODEL_KEY);
		return employeeDO;
	}

	private String getVoucherNO() {
		Random rand = new Random();// 生成随机数
		String voucherNO = "";
		for (int a = 0; a < 8; a++) {
			voucherNO += rand.nextInt(10);// 生成8位数字
		}
		return voucherNO;
	}
}
